<?php
declare (strict_types = 1);

namespace app;

use think\App;
use think\exception\ValidateException;
use think\Validate;
use EasyWeChat\Factory;
use think\facade\Cache;
use \think\facade\Db;

/**
 * 控制器基础类
 */
abstract class BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;
	
	protected $domain = 'https://yl.lizuzhe.com';

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app)
    {
        $this->app     = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {
		$this->checkToken();
    }
	// 获取用户id
	protected function getUserId()
	{
		$redis = Cache::store('redis');
		 $token= '';
		if(isset($this->request->header()['token'])){
			$token = $this->request->header()['token'];
		}
		$id = $redis->get($token);
		return $id;
	}
    // 获取管理员id
	protected function getAdminId()
	{
		$redis = Cache::store('redis');
		 $token= '';
		if(isset($this->request->header()['authorization'])){
			$token = $this->request->header()['authorization'];
		}
		$id = $redis->get($token);
		return $id;
	}
	// 验证token
	protected function checkToken()
	{
		$redis = Cache::store('redis');
		$header = $this->request->header();
			
		$pathinfo = $this->request->pathinfo();
        $bool = false;
        if($pathinfo == 'admin/login') $bool = false; 
		if($pathinfo == 'api/wxlogin') $bool = false; 
		if($pathinfo == 'pay/goodsNotic') $bool = false; 
		if($pathinfo == 'excel/exportData') $bool = false; 
		if($pathinfo == 'qrController/export') $bool = false; 
		if($pathinfo == 'index/verification') $bool = false; 
		if($pathinfo == 'uplodeFile/uplodeImageLocal') $bool = false; 
		if($pathinfo == 'api/awardNotic') $bool = false; 
		if($pathinfo == 'api/autoConfirmReceive') $bool = false; 
		if($pathinfo == 'api/getGoodsList') $bool = false; 




		if($bool){
			$token = '';
			if(isset($header['token'])){
			  $token = $this->request->header()['token'];
				$this->writeLog($token,2);
			}
			if(isset($header['authorization'])){
				$token = $this->request->header()['authorization'];
				$this->writeLog($token,1);
			}
			if($token){
			   $id = $redis->get($token);  
			  if(!$id){
			         $this->returnJson(401,'请登录',[]);
			        die();
			  }
			}else{
			  
			}
		}
			
			
	}
	// 写日志
	protected function writeLog($token,$type){
		$redis = Cache::store('redis');
		$id = $redis->get($token);
		if($id){
			if($type == 1){
				$dd = [
				'admin_id'=>$id,
				'ip'=>$this->request->ip(),
				'pathinfo'=>$this->request->pathinfo(),
				'add_time'=>date("Y-m-d H:i:s"),
				];
				Db::table('admin_log')->insert($dd);
			}else{
				$dd = [
				'user_id'=>$id,
				'ip'=>$this->request->ip(),
				'pathinfo'=>$this->request->pathinfo(),
				'add_time'=>date("Y-m-d H:i:s"),
				];
				Db::table('user_log')->insert($dd);
			}
			
		}
	}

	// 快递100发货
    public function expressE100Deliver($sendName,$sendPhone,$sendAddress,$showAddressId,$kuaidicom){
		
		// 获取接收地址
		$showAddress = Db::table('user_address')
			->where('id',$showAddressId)
			->find();

	 // 参数设置
    $key = 'jeayvzRN4837';                         // 客户授权key
    $secret = '13de073a9009497b991bea4f6a420aa6';                      // 客户授权secret
	// $secret = '93672A26C889BEA308CBBA24F1E8B802';
    list($msec, $sec) = explode(' ', microtime());
    $t = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);    // 当前时间戳
    $callBackUrl = $this->domain.'/api/expressCallBack';
    $param = array (
        'kuaidicom' => $kuaidicom,              // 快递公司的编码
        'recManName' => $showAddress['name'],             // 收件人姓名
        'recManMobile' => $showAddress['phone'],           // 收件人手机号
        'recManPrintAddr' => $showAddress['address_info'],        // 收件人所在完整地址
        'sendManName' => $sendName,            // 寄件人姓名
        'sendManMobile' => $sendPhone,          // 寄件人的手机号
        'sendManPrintAddr' => $sendAddress,       // 寄件人所在的完整地址
        'callBackUrl' => $callBackUrl,           // callBackUrl订单信息回调，默认仅支持http
    );

    // 请求参数
    $post_data = array();
    $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
    $post_data['key'] = $key;
    $post_data['t'] = $t;
    $sign = md5($post_data['param'].$t.$key.$secret);
    $post_data['sign'] = strtoupper($sign);

    // $url = 'https://poll.kuaidi100.com/order/borderapi.do?method=bOrder';    // 商家寄件下单接口地址
	$url = 'https://api.kuaidi100.com/apiMock/border?method=bOrder';
    // echo '请求参数：<br/><pre>';
    // echo print_r($post_data);
    // echo '</pre>';

        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        $data = json_decode($result, true);
	return $data;
 

}

    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

    //返回json格式消息
    public function returnJson($code, $msg, $data=[])
    {
        $arr['code'] = $code;
        $arr['msg'] = $msg;
        $arr['data'] = $data;
        echo json_encode($arr);
    }
	
	// 随机生成num个不同的数字
	public function create_rand_num($num)
	{
		//定义一个包含0-9的数组
		$arr = [0,1,2,3,4,5,6,7,8,9];
		// //随机生成4个不同的数字
		$newArr = [];
		while(count($newArr) < $num){
			$key = array_rand($arr);
			if(!in_array($arr[$key],$newArr)){
				$newArr[] = $arr[$key];
			}
		}
		
		//将这四个数字组成一个字符串
		$code = implode('',$newArr);
		return $code;
		
	}
    /**
     * 微信支付
     * @return \EasyWeChat\Payment\Application
     */
    public static function getEasyWeChatPayment()
    {
		$res = Db::table('wx_config')
			->where('cid',1)
			->find();
		$config1 = [
		    // 必要配置
		    'app_id'             => $res['appid'],
		    'mch_id'             => $res['mch_id'],
		    'key'                => $res['key'],   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
		
		    // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
		    'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
		    'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！
		
		    'notify_url'         => '默认的订单回调地址',     // 你也可以在下单时单独设置来想覆盖它
		];
        return Factory::payment($config1);
    }
    /**
     * 获取小程序实例
     * @return \EasyWeChat\MiniProgram\Application
     */
    public static function getEasyWeChatMiniProgram()
    {
		$res = Db::table('wx_config')
			->where('cid',1)
			->find();
		$config2 = [
		    'app_id' => $res['appid'],
		    'secret' => $res['secret'],
		
		    // 下面为可选项
		    // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
		    'response_type' => 'array',
		
		    'log' => [
		        'level' => 'debug',
		        'file' => __DIR__.'/wechat.log',
		    ],
		];
        return Factory::miniProgram($config2);
    }
	
	/**
	 * 获取公众号实例
	 * @return \EasyWeChat\OfficialAccount\Application
	 */
	public static function  getEasyWeChatOfficialAccount()
	{
		$config = [
			'app_id' => '',
			'secret' => '',
		
			// 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
			'response_type' => 'array',
			
			'oauth' => [
				  'scopes'   => ['snsapi_base'],
			  ],
			
			//...
		];
		return Factory::officialAccount($config);
	}
	
    // 数组去重
    public static function array_unique_key($arr,$key){
        $tmp_arr = array();
        foreach($arr as $k => $v){
            if(in_array($v[$key],$tmp_arr)){
                unset($arr[$k]);
            }else{
                $tmp_arr[]=$v[$key];
            }
        }
        return $tmp_arr;
    }
	// 二维数组去重返回二维数组
	public static function array_unique($arr,$key){
	    $tmp_arr = array();
	    foreach($arr as $k => $v){
	        if(in_array($v[$key],$tmp_arr)){
	            unset($arr[$k]);
	        }else{
	            $tmp_arr[]=$v[$key];
	        }
	    }
	    return $arr;
	}
}
  
  
